<script setup>
import { computed, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { cloneDeep } from 'lodash'
import { apiHome } from '@/api/healthAssessment'

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
const visible = ref(false)

const columns = [
  {
    title: '数据名称',
    dataIndex: 'dataName',
    align: 'center'
  },
  {
    title: '数据编码',
    dataIndex: 'dataCode',
    align: 'center'
  },
  {
    title: '请求地址',
    dataIndex: 'httpAddr',
    align: 'center'
  },
  {
    title: '操作',
    slotName: 'action',
    align: 'center'
  }
]
const scroll = {
  x: '100%',
  maxHeight: '262px'
}
const tableLoading = ref(false)
const taskPageData = ref([])

const dialogTitle = computed(() => {
  switch (dialogType.value) {
    case 'add':
      return '添加参数'
    case 'edit':
      return '修改参数信息'
    default:
      return ''
  }
})

const dialogType = ref('add')
const paramsFormRef = ref()

const DEFAULT_TASK_FORM = {
  dataName: '',
  dataCode: '',
  httpAddr: ''
}

const paramsFormRules = {
  dataName: [{ required: true, message: '请填写数据名称', trigger: ['change', 'input'] }],
  dataCode: [{ required: true, message: '请填写数据编码', trigger: ['change', 'input'] }]
}

const paramsForm = ref(cloneDeep(DEFAULT_TASK_FORM))
const handleAdd = () => {
  dialogType.value = 'add'
  visible.value = true
}

const handleSubmit = async () => {
  const API = dialogType.value === 'add' ? apiHome.addParamsAPI : apiHome.editParamsAPI
  if (!paramsFormRef.value) return false
  const res = await paramsFormRef.value.validate()
  if (res !== undefined) return false
  try {
    const { code, data, message } = await API(paramsForm.value)
    if (code === 200) {
      Message.success(message || data)
      await loadList()
      return true
    } else {
      Message.error(message || data)
      return false
    }
  } catch (errors) {
    console.log('校验失败:', errors)
    return false
  }
}

const resetForm = () => {
  if (paramsFormRef.value) {
    paramsFormRef.value.clearValidate()
    paramsForm.value = cloneDeep(DEFAULT_TASK_FORM)
  }
}
const handleBeforeClose = () => {
  resetForm()
}

const loadList = async () => {
  try {
    tableLoading.value = true
    const { code, data } = await apiHome.getParamsPageListAPI({
      page: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    })
    if (code === 200) {
      tableLoading.value = false
      taskPageData.value = data.list
      pagination.value.total = Number(data.total)
    }
  } catch (e) {
    console.log(e)
  } finally {
    tableLoading.value = false
  }
}
loadList()

const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadList()
}

const handlePageSizeChange = (size) => {
  pagination.value.pageSize = size
  loadList()
}

const handleEdit = async (record) => {
  dialogType.value = 'edit'
  paramsForm.value = record
  visible.value = true
}
const handleDelete = (record) => {
  Modal.confirm({
    title: '提示',
    content: `确定要删除【${record.dataName}】这个参数吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        const { code, message } = await apiHome.delParamsAPI([record.id])
        if (code === 200) {
          Message.success('删除成功')
        } else {
          Message.error(message || '删除失败')
        }
      } catch (e) {
        console.log(e)
      } finally {
        await loadList()
      }
    }
  })
}
</script>

<template>
  <div class="component-params-manage">
    <div class="table-card">
      <div class="table-card-header">
        <div class="table-card-header-right">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-plus />
            </template>
            新建
          </a-button>
        </div>
      </div>
      <a-table
        class="table-main"
        :columns="columns"
        :data="taskPageData"
        :pagination="false"
        :scroll="scroll"
        :scrollbar="false"
        :loading="tableLoading"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #action="{ record }">
          <a-button size="mini" type="text" @click="handleEdit(record)">
            <template #icon>
              <IconEdit />
            </template>
            修改
          </a-button>
          <a-button status="danger" size="mini" type="text" @click="handleDelete(record)">
            <template #icon>
              <IconDelete />
            </template>
            删除
          </a-button>
        </template>
      </a-table>
      <div class="table-card-footer">
        <a-pagination
          :total="pagination.total"
          :current="pagination.page"
          :page-size="pagination.pageSize"
          show-total
          @change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
    </div>
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :on-before-ok="handleSubmit"
      :onBeforeClose="handleBeforeClose"
      unmountOnClose
    >
      <a-form :model="paramsForm" ref="paramsFormRef" auto-label-width :rules="paramsFormRules">
        <a-form-item field="dataName" label="数据名称" :validate-trigger="['change', 'input']">
          <a-input v-model="paramsForm.dataName" placeholder="数据名称" allow-clear />
        </a-form-item>
        <a-form-item field="dataCode" label="数据编码" :validate-trigger="['change', 'input']">
          <a-input v-model="paramsForm.dataCode" placeholder="数据编码" allow-clear />
        </a-form-item>
        <a-form-item field="httpAddr" label="请求地址" :validate-trigger="['change', 'input']">
          <a-input v-model="paramsForm.httpAddr" placeholder="请求地址" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
.component-params-manage {
  .table-card {
    &-header {
      margin-bottom: 8px;

      &-right {
        text-align: right;
      }
    }

    :deep(.table-main) {
      .arco-table-cell {
        padding: 8px;
      }
    }

    &-footer {
      margin-top: 8px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
